const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const { testConnection } = require('./config/db');

// 加载环境变量
dotenv.config();

// 创建Express应用
const app = express();

// CORS配置
const corsOptions = {
  origin: ['https://pjgtkgbn.manus.space', 'https://vzmvylap.manus.space', 'http://localhost:3000'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
};

// 中间件
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 导入路由
const authRoutes = require('./routes/authRoutes');
const categoryRoutes = require('./routes/categoryRoutes');
const protocolRoutes = require('./routes/protocolRoutes');
const codeGeneratorRoutes = require('./routes/codeGeneratorRoutes');

// 使用路由
app.use('/api/auth', authRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/protocols', protocolRoutes);
app.use('/api/generator', codeGeneratorRoutes);

// 基本路由
app.get('/', (req, res) => {
  res.json({ message: '欢迎使用通讯协议可视化生成器API' });
});

// 测试数据库连接
testConnection()
  .then(connected => {
    if (!connected) {
      console.warn('警告: 数据库连接失败，某些功能可能不可用');
    }
  })
  .catch(err => {
    console.error('数据库连接测试失败:', err);
  });

// 设置端口
const PORT = process.env.PORT || 3000;

// 启动服务器
app.listen(PORT, '0.0.0.0', () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app;
